import 'dart:convert';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_app/store.dart';
import 'package:flutter_app/utils/http.dart';
import 'package:oktoast/oktoast.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPage createState() => _LoginPage();
}

class _LoginPage extends State<LoginPage> {

  @override
  void initState(){
    super.initState();
    getImage();
  }

  var decodeImg = Container();
  var deviceId;

  // 获取验证码
  getImage() async{
    ResultData res = await HttpRequest.post('/uaa/auth/code/image', null, header:{'Content-Type':'application/json'});
    if(res.code == 0){
      Uint8List bytes = Base64Decoder().convert(res.data['image']);
      deviceId = res.data['deviceId'];
      setState(() =>
        decodeImg = Container(
          height: 45,
          margin: EdgeInsets.only(left: 15.0),
          child:Listener(
            child: Image.memory(
              bytes,
              fit: BoxFit.fill,
              gaplessPlayback:true
            ),
            onPointerDown:(event) => getImage()
          )
        )
      );
    }
  }
  GlobalKey _formKey = new GlobalKey<FormState>();
  TextEditingController _nameController = new TextEditingController();
  TextEditingController _pwdController = new TextEditingController();
  TextEditingController _vorController = new TextEditingController();
  bool pwdShow = false;
  //  登陆
  login() async{
    if ((_formKey.currentState as FormState).validate()) {
      ResultData res = await HttpRequest.post('/uaa/auth/form', {
        'username':_nameController.text,
        'password':_pwdController.text,
        'imageCode':_vorController.text,
        'deviceId':deviceId
      });
      // 登陆成功
      if(res.code == 0){
        // User user = Provider.of<User>(context);
        // var user = context.watch<User>();
        User user = new User();
        await user.setUser('',res.data['access_token']);
        // user.setUser('', res.data['access_token']);
        // var user = context.read<User>();
        // print(user.token);
        Navigator.of(context).pushNamed('/homePage');
      }else{
        showToast(res.msg);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // Scaffold 完整导航
    // SafeArea 异形屏幕适配
    // Container 容器
    return Scaffold(
      // 防止键盘问题
      resizeToAvoidBottomPadding: false,
      body: SingleChildScrollView(
        child:Container(
            padding: EdgeInsets.only(top:100,left: 40.0, right: 40),
            child: Column(
                children: [
                  Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            Text("Neusoft", style: TextStyle(fontSize: 60.0,color: Colors.blueAccent, fontWeight: FontWeight.w700))
                          ],
                        )
                      ]
                  ),
                  Container(
                      margin: EdgeInsets.only(top: 30, bottom: 60),
                      child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: <Widget>[
                            Text("东软园区安防守护", style: TextStyle(fontSize: 16.0,color: Colors.black87, fontWeight: FontWeight.w400))
                          ]
                      )
                  ),
                  Form(
                    key: _formKey,
                    child: Column(
                        children: [
                          TextFormField(
                              autofocus: false,
                              controller: _nameController,
                              decoration: InputDecoration(
                                  labelText: "账号",
                                  hintText: "请输入账号",
                                  prefixIcon: Icon(Icons.person)
                              ),
                              // 校验用户名（不能为空）
                              validator: (v) {
                                return v.trim().isNotEmpty ? null : '账号不能为空';
                              }
                          ),
                          TextFormField(
                              autofocus: false,
                              controller:_pwdController,
                              decoration: InputDecoration(
                                  labelText: "密码",
                                  hintText: "请输入密码",
                                  prefixIcon: Icon(Icons.lock),
                                  suffixIcon: IconButton(
                                      icon: Icon(pwdShow ? Icons.visibility_off : Icons.visibility),
                                      onPressed: () {
                                        setState(() {
                                          pwdShow = !pwdShow;
                                        });
                                      }
                                  )
                              ),
                              obscureText: !pwdShow,
                              validator: (v) {
                                return v.trim().isNotEmpty ? null : '密码不能为空';
                              }
                          ),
                          Flex(
                              direction: Axis.horizontal,
                              children: [
                                Expanded(
                                    flex: 3,
                                    child: TextFormField(
                                      autofocus: false,
                                      controller:_vorController,
                                      decoration: InputDecoration(
                                          labelText: "验证码",
                                          hintText: "请输入验证码",
                                          prefixIcon: Icon(Icons.security)
                                      ),
                                      validator: (v) {
                                        return v.trim().isNotEmpty ? null : '验证码不能为空';
                                      }
                                    )
                                ),
                                Expanded(
                                    flex: 2,
                                    child:decodeImg
                                )
                              ]
                          ),
                          Container(
                              margin: EdgeInsets.only(top:70),
                              width: double.infinity,
                              height: 40.0,
                              child: new RaisedButton(
                                color: Colors.blueAccent,
                                child: Text("登录",style: TextStyle(fontSize: 16.0,color: Colors.white)),
                                // 设置按钮圆角
                                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
                                onPressed: login
                              )
                          )
                        ]
                    ),
                  ),
                ]
            )
        )
      )
    );
  }
}